<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>设备运行状态</title>
</head>
<link href="../../css/index.css" rel="stylesheet">

<body>
  <div id="status-content">
    <div class="message" :class="message.type" v-if="message.text">{{message.text}}</div>
    <!-- <div class="edit-content">
      <select v-model="addSubId" style="width: 300px;text-align: center;" placeholder="新增子区">
        <option v-for="item in localBaseMsg" :key="item.subId" :value="item.subId">{{item.subId}}</option>
      </select>
      <button class="primary-btn" @click="handleAdd">
        新增时段
      </button>
    </div> -->
    <table border="1">
      <tr>
        <th class="area-title">所属子区</th>
        <th class="area-title">序号</th>
        <th class="area-title">开始时间</th>
        <th class="area-title">结束时间</th>
        <th class="area-title">是否启用</th>
        <th class="area-title">主相位配置</th>
        <th class="area-title">操作</th>
      </tr>
      <tr class="center" v-for="(item, index) in timeData" :class="index % 2 === 0 ? 'odd' : 'even'" :key="item.ssId">
        <td>{{item.ssId}}</td>
        <td>{{index + 1}}</td>
        <td>{{item.startTime}}</td>
        <td>{{item.endTime}}</td>
        <td>{{TIME_FLT[item.runEnable]}}</td>
        <td>{{item.stretch}}</td>
        <td>
          <button @click="handleEditTime(item)" :class="onlyRead ? 'disabled-btn': ''" >
            编辑
          </button>
          <button @click="handleDelTime(item)" class="del-btn-text" :class="!ableDelete ? 'disabled-btn': ''">
            <img src="../../assets/jiazai.png" v-if="loading.deleteTime" class="loading" />
            删除
          </button>
        </td>
      </tr>
      <tr v-if="loading.table">
        <th colspan="13">
          <img src="../../assets/jiazai.png" class="loading" />
        </th>
      </tr>
    </table>
    <!-- 时段配置弹窗 -->
    <div class="drawer" style="width: 500px;" :class="currentEditData?.ssId ? '' : 'hidden-scheme'">
      <div class="drawer-title" v-if="currentEditData && currentEditData.ssId">
        <div>
          子区【{{currentEditData.ssId}}】- 时段配置
        </div>
        <div @click="handleTimeCancel">
          <img src="../../assets/guanbi.png" />
        </div>
      </div>
      <div class="drawer-content" v-if="currentEditData.ssId">
        <div>
          <table>
            <tr>
              <th colspan="2">路口</th>
              <th colspan="2">主相位</th>
            </tr>
            <tr class="center" v-for="item in currentEditData.phaseList" :key="item.key">
              <td colspan="2">{{item.key}}</td>
              <td colspan="2"><input v-model="item.value" style="width: 60%; text-align: center;"/></td>
            </tr>
            <tr class="center">
              <td>开始时间</td>
              <td style="width: 160px;">
                <input
                  v-model="currentEditData.startTime"
                  style="width: 100%;text-align: center;"
                  />
              </td>
              <td>结束时间</td>
              <td style="width: 160px;">
                <input
                v-model="currentEditData.endTime"
                style="width: 100%;text-align: center;"/>
              </td>
            </tr>
            <tr class="center">
              <td>是否启用</td>
              <td colspan="3">
                <select
                  v-model="currentEditData.runEnable"
                  style="width: 100%;text-align: center;"
                  >
                  <option v-for="item in timeStatus" :key="item.key" :value="item.key">{{item.label}}</option>
              </td>
            </tr>
          </table>
        </div>
      </div>
      <div class="drawer-footer">
        <button class="cancel-btn" @click="handleTimeCancel">取消</button>
        <button class="primary-btn" @click="handleTimeSure">
          <img src="../../assets/jiazai.png" v-if="loading.editTime" class="loading" />
          确定
        </button>
      </div>
    </div>
  </div>
</body>
<script src="../../config.js"></script>
<script src="../../js/vue3.js"></script>
<script src="../../js/mock/firstEdition/timeMock.js"></script>
<script>
  const {createApp, ref, nextTick, reactive, onMounted, onUnmounted, watch, computed} = Vue
  const app = createApp({
    setup() {
      const tabList = [
        {key: 'device', label: '设备状态'},
        {key: 'time', label: '时段配置'},
      ]

      const MESSAGE_TYPE = {
        'SUCCESS': 'success',
        'INFO': 'info',
        'ALERT': 'alert',
        'ERROR': 'error'
      }

      const loading = reactive({
        reload: false, // 刷新时段
        open: false, // 开启子区开关
        close: false, // 关闭子区开关
        table: false, // 表格刷新
        editTime: false, // 编辑时段
        deleteTime: false, // 删除时段
      })

      const message = reactive({
        type: '',
        text: ''
      })

      // 弹窗消息1.5秒消失
      watch(
        () => message.text,
        () => {
          if(message.text) {
            setTimeout(() => {
              message.text = ''
            }, 2000)
          }
        }
      )

      // ------------- 时段配置 ---------------
      let timeData = ref([])

      const timeStatus = [
        { key: 0, label: '关闭' },
        { key: 1, label: '开启' },
      ]

      const TIME_FLT = {
        0: '关闭',
        1: '开启'
      }

      // 是否能删除
      const ableDelete = ref(false)
      // 是否能编辑状态
      const ableEditStretch = ref(false)
      // 是否仅读
      const onlyRead = ref(false)
      // 获取时段表配置
      const getTimeConfig = () => {
        loading.table = true
        fetch(apiUrl + '/utch-itsg/schedule/listAll')
        .then(res => res.json())
        .then(res => {
          console.log('res', res)
          ableDelete.value = res.data.ableDelete
          ableEditStretch.value = res.data.ableEditStretch
          onlyRead.value = res.data.onlyRead
          timeData.value = res.data.scheduleList
        })
        .catch(error => {
          message.text = error.msg || '列表返回数据失败'
          message.type = MESSAGE_TYPE.ERROR
        }).finally(() => {
          loading.table = false
          if (isMock) {  
            message.text = '请注意当前处于mock模式'
            message.type = MESSAGE_TYPE.INFO
            timeData.value = timeConfig.data.scheduleList
          }
        })
      }

      const currentEditData = reactive({
        endTime: '',
        id: '',
        runEnable: 0,
        ssId: '',
        startTime: '',
        stretch: {},
        phaseList: []
      })
      // 编辑时段
      const handleEditTime = (item) => {
        for(let i in currentEditData) {
          currentEditData[i] = item[i]
        }
        initPhaseList()
      }

      // 初始化相位信息
      const initPhaseList = () => {
        currentEditData.phaseList = []
        if (currentEditData.stretch) {
          for(let i in currentEditData.stretch) {
            currentEditData.phaseList.push({
              key: i,
              value: currentEditData.stretch[i]
            })
          }
        }
      }

      // 删除时段
      const handleDelTime = (item) => {
        if (!ableDelete.value) return
        const result = confirm('您确定要删除吗?')
        console.log('result', result)
        if (result === true) {
          loading.deleteTime = true
          fetch(apiUrl + '/utch-itsg/schedule/delete', {
            method: 'POST',
            body: JSON.stringify({
              confirm: 'true',
              ids: [item.id]
            }),
            headers: {
              'content-type': 'application/json'
            }
          }).then(res => res.json())
          .then(() => {
            // message.text = `删除成功`
            // message.type = MESSAGE_TYPE.SUCCESS
            if (res.code === 200) {
              message.text = `删除成功`
              message.type = MESSAGE_TYPE.SUCCESS
              getTimeConfig()
              handleTimeCancel()
            }
            else {
              message.text = res.msg || `修改时段失败`
              message.type = MESSAGE_TYPE.ERROR
            }
            getTimeConfig()
          }).catch((error) => {
            message.text = error.msg || `删除失败`
            message.type = MESSAGE_TYPE.ERROR
          }).finally(() => {
            loading.deleteTime = false
          })
        }
      }

      // 取消编辑
      const handleTimeCancel = () => {
        for(let i in currentEditData) {
          currentEditData[i] = ''
        }
        currentEditData.runEnable = 0
        currentEditData.stretch = {}
      }

      // 确定修改
      const handleTimeSure = () => {
        loading.editTime = true
        const stretch = {}
        currentEditData.phaseList.forEach((item) => {
          stretch[item.key] = item.value
        })
        const data = {
          ...currentEditData,
          stretch: stretch
        }
        Reflect.deleteProperty(data, 'phaseList')
        console.log('data', data);
        
        fetch(apiUrl + '/utch-itsg/schedule/update', {
          method: 'POST',
          headers: {
            'content-type': 'application/json'
          },
          body: JSON.stringify(data)
        }).then(res => res.json())
        .then((res) => {
          if (res.code === 200) {
            message.text = `修改时段成功`
            message.type = MESSAGE_TYPE.SUCCESS
            getTimeConfig()
            handleTimeCancel()
          }
          else {
            message.text = res.msg || `修改时段失败`
            message.type = MESSAGE_TYPE.ERROR
          }
        })
        .catch(error => {
          message.text = error.msg || `修改时段失败`
          message.type = MESSAGE_TYPE.ERROR
        }).finally(() => {
          loading.editTime = false
        })
      }

      // 新增时段
      const handleAdd = () => {
        if (!addSubId.value) {
          message.text = '请选择子区'
          message.type = MESSAGE_TYPE.INFO
          return
        }
        const result = localBaseMsg.value.find(item => item.subId === addSubId.value)
        handleTimeCancel()
        currentEditData.ssId = result.subId
        result.siteStatuses.forEach(item => {
          currentEditData.stretch[item.siteId] = ''
        })
        initPhaseList()
      }

      const addSubId = ref()
      // 缓存的信息
      const localBaseMsg = ref({})
      onMounted(() => {
        getTimeConfig()
        nextTick(() => {
          const data = window.localStorage.getItem('BASE_DICTS')
          data && (localBaseMsg.value = JSON.parse(data).subMsg)
        })
      })

      return {
        message,
        loading,
        tabList,
        timeData,
        currentEditData,
        timeStatus,
        TIME_FLT,
        ableEditStretch,
        ableDelete,
        onlyRead,
        localBaseMsg,
        addSubId,
        handleEditTime,
        handleDelTime,
        handleTimeCancel,
        handleTimeSure,
        handleAdd
      }
    }
  })
  app.mount("#status-content");
</script>

</html>